package com.lwq.util;

import java.io.FileReader;
import java.io.LineNumberReader;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;

public class JsUtil {
	private Context cx = null;   
    private Scriptable scope = null;
    private Script script = null;
    private  String CCImportStr = null;
    private static JsUtil instance = null;
    
    
    public JsUtil()   
    {   
        this.cx = Context.enter();   
        this.scope = cx.initStandardObjects();   
        CCImportStr = getJsString(Constance.CCIMPROT_JS_PATH);
    }   
  
    public static JsUtil getInstance(){
    	if(instance == null){
    		instance = new JsUtil();
    	}
    	return instance;
    }

	public void compileString(String ...filename)   
    {   
        String jsContent = mixJsString(filename);   
        script = cx.compileString(jsContent, null, 1, null);
        script.exec(Context.getCurrentContext(), scope);
    }   
  
    private String mixJsString(String ...filename)  {
    	String jsStr = "";
    	if(filename == null){
    		return jsStr;
    	}
    	for(String file:filename){
    		jsStr += getJsString(file);
    	}
		return jsStr;
    }
    
    public String getJsString(String filename)   
    {   
        LineNumberReader reader;   
        try  
        {   
            reader = new LineNumberReader(new FileReader(filename));   
            String s = null;   
            StringBuffer sb = new StringBuffer();   
            while ((s = reader.readLine()) != null)   
            {   
                sb.append(s).append("\n");   
            }   
            return sb.toString();   
        }   
        catch (Exception e)   
        {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
            return null;   
        }   
    }   
    
    public Object runCmd(String cmd) {
    	String runStr = CCImportStr;
    	if(runStr != null){
    		runStr = runStr.replaceAll("ProcessReplaceString", cmd);
    		cx.evaluateString(scope, runStr, null, 1, null);
 	        Function fc = (Function) scope.get("getProcessReslut", scope);   
 	        return fc.call(Context.getCurrentContext(), scope, fc, null);
    	}
    	return null;
    }
    
    public Script getScript() {
		return script;
	}
    public Scriptable getScope()   
    {   
        return scope;   
    }   
    public String getCCImportStr()   
    {   
        return CCImportStr;   
    }   
}
